#pragma once

#include <functional>
#include "Socket.hpp"
#include "InetAddr.hpp"

using namespace socket_ns;

static const int gport = 8888;

using service_io_t = std::function<void(SockSPtr, InetAddr &)>;

class TcpServer
{
public:
    TcpServer(service_io_t service, int port = gport)
        : _port(port),
          _listensock(std::make_shared<TcpSocket>()),
          _isrunning(false),
          _service(service)
    {
        _listensock->BuildListenSocket(_port);
    }

    class ThreadData
    {
    public:
        ThreadData(SockSPtr sockfd, TcpServer *self, const InetAddr &addr)
            : _sockfd(sockfd),
              _self(self),
              _addr(addr)
        {
        }
        ~ThreadData()
        {
        }

    public:
        SockSPtr _sockfd;
        TcpServer *_self;
        InetAddr _addr;
    };

    void Loop()
    {
        // 方式2：也可以用信号的方式，避免等待
        // signal(SIGCHLD, SIG_IGN);

        _isrunning = true;
        while (_isrunning)
        {
            InetAddr client;
            SockSPtr newsocket = _listensock->Accepter(&client);
            if (newsocket == nullptr)
                continue;

            LOG(INFO, "get a new link, client info: [%s], newsocket: %d\n", client.AddrStr().c_str(), newsocket->Sockfd());

            // 版本2 -- 多线程版本
            // 这里就没有"多余的文件描述符"这一说法了，因为新主线程共享文件描述符表，不能关闭
            pthread_t tid;
            ThreadData *td = new ThreadData(newsocket, this, client);
            pthread_create(&tid, nullptr, Excute, td);
        }
        _isrunning = false;
    }
    static void *Excute(void *arg)
    {
        pthread_detach(pthread_self()); // 线程分离

        ThreadData *td = static_cast<ThreadData *>(arg);
        td->_self->_service(td->_sockfd, td->_addr);
        td->_sockfd->Close();

        delete td;
        return nullptr;
    }

    ~TcpServer()
    {
    }

private:
    SockSPtr _listensock;
    uint16_t _port;
    bool _isrunning;
    service_io_t _service;
};